package net.mygwt.ui.client.widget.table;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.WidgetHelper;

import net.mygwt.ui.client.Events;
import net.mygwt.ui.client.MyDOM;
import net.mygwt.ui.client.event.BaseEvent;

public class EditTableItem extends TableItem {
	
	private boolean editmode= false;
	
	public EditTableItem(Object[] values) {
		super(values);
	}
	
	public void onBaseEvent(BaseEvent be) {
		//only if not in edit mode
		if(!editmode) {
			switch (be.type) {
			case Events.Click:
				onClick(be);
				break;
			case Events.DoubleClick:
				onDoubleClick(be);
				break;
			case Events.MouseOver:
				onMouseOver(be);
				break;
			case Events.MouseOut:
				onMouseOut(be);
				break;
			}
		}
	}


	public void edit(int index, Widget editor) {
	  if (rendered) {
	    if(editor != null) {
	      Object editItemValue= getValue(index);
	      if(editItemValue != null) {
	        System.err.println("editItemValue = " + editItemValue);
	        if(editor instanceof HasValue) {
	          ((HasValue)editor).setValue(editItemValue);
	        } else if(editor instanceof HasText) {
	          if(editItemValue == null) {
	            ((HasText)editor).setText("");
	          } else {
	            ((HasText)editor).setText(editItemValue.toString());
	          }
	        }
          }
          
	      Element edElement= editor.getElement();
	      MyDOM.setStyleName(edElement, "my-tbl-col-edit-text");
	      int w = getTable().getColumnModel().getWidthInPixels(index) - 10;
	      MyDOM.setStyleAttribute(edElement, "width", w+"px");
	      setWidget(index, editor);
//	      System.err.println("ED ELEMENT : " + edElement);
//	      WidgetHelper.doAttach(editor);
	      setData("preedit:"+index, editItemValue);
	    }
	    setEditModeOn();
	  }
	}

//	CHANGE - commit any editing and close editor on column item
	public void commitEdit(int i, Widget editor) {
		if(editor != null) {
//			if(editor instanceof HasFocus) {
//				((HasFocus)editor).setFocus(false);
//			}
			if(editor instanceof HasValue) {
				setValue(i, ((HasValue)editor).getValue());
			} else if(editor instanceof HasText) {
				String val= ((HasText)editor).getText();
				setText(i, val);
			}
			WidgetHelper.doDetach(editor);
		}
		setEditModeOff();
	}

	//cancel any editing and close editor on column item
	public void cancelEdit(int i, Widget editor) {
		if(editor != null) {
			Object val= getData("preedit:"+i);
			setValue(i, val);
			WidgetHelper.doDetach(editor);
		}
		setEditModeOff();
	}

	//BEGIN Edit
	protected void setEditModeOn() {
		disableTextSelection(false);
		getTable().disableTextSelection(false);
		editmode= true;
	}

	//End Edit
	protected void setEditModeOff() {
		disableTextSelection(true);
		getTable().disableTextSelection(true);
		editmode= false;
	}
	
}
